require('es6-promise').polyfill();
import router from '@/router';
import config from '../config/config';
import validateUtil from './validateUtil';
export default class commonUtil {
    //调转至登录页
    static skipLogin() {
        this.skip(config.constantConfig.loginUrlConstant);
    };
    //跳转路由
    static skip(name) {
        router.push({
            name: name
        });
    };

    static downLoadClick(blob, fileName) {
        if ('download' in document.createElement('a')) { // 非IE下载
            const elink = document.createElement('a')
            elink.download = fileName;
            elink.style.display = 'none';
            elink.href = URL.createObjectURL(blob);
            document.body.appendChild(elink);
            elink.click();
            URL.revokeObjectURL(elink.href); // 释放URL 对象
            document.body.removeChild(elink);
        } else { // IE10+下载
            navigator.msSaveBlob(blob, fileName)
        }
    }

    //带参数跳转
    static skipParam(path, queryObj) {
        router.push({
            path: path,
            query: queryObj
        });
    };
    //图片请求统一处理
    static requestHandleImg(obj, name) {
        obj[name] = this.removeImgPrefix(obj[name]);
    }
    //图片返回统一处理
    static responseHandleImg(obj, field) {
        obj[field] = this.addImgPrefix(obj[field]);
    }
    //添加图片及视频前缀
    static addImgPrefix(val) {
        if (validateUtil.isNotNull(val) && !(validateUtil.startWith(val, "http://") || validateUtil.startWith(val, "https://")))
            return config.rootConfig.imgRootPath + val;
        return val;
    }
    //删除图片及视频前缀
    static removeImgPrefix(val) {
        if (validateUtil.isNotNull(val) && validateUtil.startWith(val, "http://") || validateUtil.startWith(val, "https://"))
            return val.replace(config.rootConfig.imgRootPath, '');
        return val;
    }
    //分页数据处理
    static responseHandlePage(pageResult, callHandlePageSingleData) {
        let dataList = [];
        for (let j = 0, len = pageResult["list"].length; j < len; j++)
            dataList[j] = callHandlePageSingleData(pageResult["list"][j]); //处理列表
        pageResult["list"] = dataList;
        return pageResult;
    }
    //list数据处理
    static responseHandleList(list, callHandleListSingleData) {
        let dataList = [];
        for (let j = 0, len = list.length; j < len; j++)
            dataList[j] = callHandleListSingleData(list[j]); //处理列表
        list = dataList;
        return dataList;
    }
    //获取路由
    static getRequestRouter() {
        let url = window.location.href.toString();
        url = url.replace("/?#/", "#");
        if (url.indexOf("#/") > 0)
            url = url.substring(url.indexOf("#/") + 2, url.length);
        if (url.indexOf("?") > 0)
            url = url.substring(0, url.indexOf("?"));
        return url;
    };
    //获取?后的参数
    static getRequestParam() { //获取参数后的参数
        let url = window.location.href.toString();
        url = url.replace("/?#/", "#");
        let urlArray = url.split("?");
        let result = {};
        if (validateUtil.isNotNull(urlArray) && urlArray.length == 2) {
            let params = urlArray[1].split("&");
            for (let i = 0; i < params.length; i++)
                result[params[i].split("=")[0]] = unescape(params[i].split("=")[1]);
        }
        return result;
    };
    //获取参数中的值
    static getRequestParamByKey(key) {
        let params = this.getRequestParam() || {};
        return params[key];
    }
    //日期处理
    static formatDateByHyphen(dateInt) {
        if (validateUtil.isNull(dateInt) || !validateUtil.isNumber(dateInt))
            return "";
        let date = dateInt.toString();
        return date.substr(0, 4) + "-" + date.substr(4, 2) + "-" + date.substr(6, 2);
    };
    //格式化日期
    static formatDateBySplit(dateInt) {
        if (validateUtil.isNull(dateInt) || !validateUtil.isNumber(dateInt))
            return "";
        let date = dateInt.toString();
        return date.substr(0, 4) + "/" + date.substr(4, 2) + "/" + date.substr(6, 2);
    };
    //中文格式化日期
    static formatDateByCn(dateInt) {
        if (validateUtil.isNull(dateInt) || !validateUtil.isNumber(dateInt))
            return "";
        let date = dateInt.toString();
        return date.substr(0, 4) + "年" + date.substr(4, 2) + "月" + date.substr(6, 2) + "日";
    };
    //处理6位时间
    static formatSixTime(timeInt) {
        if (validateUtil.isNull(timeInt) || !validateUtil.isNumber(timeInt))
            return "";
        let result = "";
        if (timeInt > 0) {
            result = timeInt % 100;
            timeInt = parseInt(timeInt / 100);
        }
        if (timeInt > 0) {
            result = timeInt % 100 + ":" + result;
            timeInt = parseInt(timeInt / 100);
        }
        if (timeInt > 0)
            result = timeInt % 100 + ":" + result;
        return result;
    };
    //处理9位时间
    static formatNineTime(timeInt) {
        if (validateUtil.isNull(timeInt) || !validateUtil.isNumber(timeInt))
            return "";
        let result = "";
        if (timeInt > 0) {
            result = timeInt % 1000;
            timeInt = parseInt(timeInt / 1000);
        }
        if (timeInt > 0) {
            result = timeInt % 100 + "." + result;
            timeInt = parseInt(timeInt / 100);
        }
        if (timeInt > 0) {
            result = timeInt % 100 + ":" + result;
            timeInt = parseInt(timeInt / 100);
        }
        if (timeInt > 0)
            result = timeInt % 100 + ":" + result;
        return result;
    };
    //中文时间
    static formatSixTimeCn(timeInt) {
        if (validateUtil.isNull(timeInt) || !validateUtil.isNumber(timeInt))
            return "";
        let result = "";
        if (timeInt > 0) {
            result = timeInt % 100 + "秒";
            timeInt = parseInt(timeInt / 100);
        }
        if (timeInt > 0) {
            timeInt = timeInt % 100;
            result = timeInt % 100 + "分" + result;
        }
        if (timeInt > 0) {
            timeInt = timeInt % 100;
            result = timeInt % 100 + "时" + result;
        }
        return result;
    };

    static formatNineTimeCn(timeInt) {
        if (validateUtil.isNull(timeInt) || !validateUtil.isNumber(timeInt))
            return "";
        let result = "";
        if (timeInt > 0) {
            result = timeInt % 1000 + "毫秒";
            timeInt = timeInt / 1000;
        }
        if (timeInt > 0) {
            result = timeInt % 100 + "秒" + result;
            timeInt = timeInt / 100;
        }
        if (timeInt > 0) {
            timeInt = timeInt % 100;
            result = timeInt % 100 + "分" + result;
        }
        if (timeInt > 0) {
            timeInt = timeInt % 100;
            result = timeInt % 100 + "时" + result;
        }
        return result;
    };
    //转化为菜单列表
    static arrayToTreeByPermission(list) {
        return this.arrayToTree(list, "id", "pId", "children", "")
    }
    //角色选择菜单
    static arrayToTreeByPerMenu(list) {
        return this.arrayToTree(list, "employeePermissionId", "pId", "children", "")
    }
    //目录菜单
    static arrayToTreeByCatalog(list) {
        return this.arrayToTree(list, "id", "pId", "subs", "")
    }
    //菜单
    static arrayToTreeByMenu(list, rootVal) {
        return this.arrayToTree(list, "id", "pId", "subs", rootVal)
    }

    //数组转属性结构
    static arrayToTree(list, idName, pidName, childrenName, rootVal) {
        list.forEach(element => {
            let parentId = element[pidName];
            if (validateUtil.isNotNull(parentId)) {
                list.forEach(ele => {
                    if (ele[idName] == parentId) {
                        if (!ele[childrenName])
                            ele[childrenName] = [];
                        ele[childrenName].push(element);
                    }
                });
            }
        });
        list = list.filter(ele => ele[pidName] === rootVal);
        return list;
    }
    //格式化Money
    static formatMoney(money) {
        if (validateUtil.isNull(money) || !validateUtil.isNumber(money))
            return "";
        let tmp = parseInt(money);
        let result = "";
        if (tmp > 100000000) {
            result += tmp / 100000000 + "亿";
            tmp = tmp % 100000000;
        }
        if (tmp > 10000) {
            result += tmp / 10000 + "万";
            tmp = tmp % 10000;
        }
        result += tmp + "元";
        return result;
    };
    //格式化天
    static formatDays(days) {
        if (validateUtil.isNull(days) || !validateUtil.isNumber(days))
            return "";
        let day = parseInt(days);
        let result = "";
        if (day > 365) {
            result += day / 365 + "年";
            day = day % 365;
        }
        if (day > 30) {
            result += day / 30 + "月";
            day = day % 30;
        }
        result += day + "天";
        return result;
    };
    // static setInterval(){
    //   setInterval(()=>{
    //     self.currentList()
    //     new Promise(resolve =>{
    //       // resolve(self.faceCountList())
    //       resolve()
    //     }).then(val=>{
    //       return new Promise(resolve => {
    //         setTimeout(() => {
    //           // resolve(self.warningList())
    //         }, 1000)
    //       })
    //     }).then(val=>{
    //       return new Promise(resolve =>{
    //         setTimeout(()=>{
    //           // resolve(self.companyList())
    //         },1000)
    //       })
    //     })
    //   },3000)
    // }

    //json 转url Params
    static formatterUrlParams(data) {
        if (!data) {
            return ''
        }
        let str = Object.keys(data).map(key => {
            return encodeURIComponent(key) + '=' + encodeURIComponent(data[key])
        }).join('&')
        return "?" + str
    }
    //urlparams转json
    static urlParamsToJson(key) {
        let str = location.search || location.href.match(/\?(\S*)/)
        if (!str) {
            return ""
        }
        if (typeof str === "string") {
            str = str.substr(1);
        } else if (str instanceof Array) {
            str = str[1]
        }
        let params = {}


        let strArray = str.split('&');
        for (let val of strArray) {
            let result = val.split('=');
            params[result[0]] = result[1]
        }
        //遍历Params 如果key有值的情况下返回对应的value,否则直接返回一个对象信息
        if (key) {
            return params[key]
        }

        return params
    }

}